<?php
/**
 * Created by PhpStorm.
 * User: zyark
 * Date: 2017/5/27
 * Time: 14:27
 */

namespace Home\Controller;


use Think\Controller;
use Home\Logic;
class ShopCartController extends BaseController
{

    public $cartLogic; // 购物车逻辑操作类
    public $user_id = 0;
    public $user = array();
    public $session_id;

    public function _initialize() {

        $this->cartLogic = new \Home\Logic\CartLogic();
        $this->session_id = session_id();
        if(session('user'))
        {
            $user = $this->getUser();
            $this->user = $user;
            $this->user_id = $user['user_id'];

        }
    }


    public function index(){
// 默认按照 session_id 查询
//        $where = " session_id = '$this->session_id' ";
        $this->user_id &&
        $where = " user_id = ".$this->user_id; // 如果这个用户已经等了则按照用户id查询
//        var_dump($this->user_id);
        $user = $this->getUser();
        $cartList = M('Cart')->where($where)->getField("id,goods_id,goods_price,goods_name,goods_num,selected,prom_type,prom_id, region_id, region_id_2,agent_price");
        foreach ($cartList as $key => $val){

            $cartList[$key]['region_pri'] = M('region')->where(array('id'=>$val['region_id']))->getField('name');
            $cartList[$key]['region_city'] = M('region')->where(array('id'=>$val['region_id_2']))->getField('name');
            $cartList[$key]['original_img'] = M('goods')->where(array('goods_id'=>$val['goods_id']))->getField('original_img');

        }
        $this->assign('cartList', $cartList);
        $this->assign('page_str','shopcart');
        $this->display('index');
    }

    public function ajaxAddCart(){
        $goods_id = I("post.goods_id"); // 商品id
        $goods_num = I("post.goods_num");// 商品数量
        $goods_spec = I("post.goods_spec"); // 商品规格
//        $this->ajaxReturn(array('msg'=>$goods_spec));
        $result = $this->cartLogic->addCart($goods_id, $goods_num, $goods_spec, $this->session_id, $this->user_id); // 将商品加入购物车
        $this->ajaxReturn($result);

    }

    /**
     * ajax 删除购物车的商品
     */
    public function ajaxDelCart()
    {
        $ids = I("id"); // 商品 ids
        $result = M("Cart")->where(" id in ($ids)")->delete(); // 删除id为5的用户数据
        $return_arr = array('status'=>1,'msg'=>'删除成功','result'=>''); // 返回结果状态
        $this->ajaxReturn($return_arr);
    }

    //确认订单
    public function  shop2(){
        $type = I('type'); //1表示从购物车过来 2表示从立即购买过来 3表示从特殊商品过来
//        $addressId = I('addressId');
//        $user = $this->getUser();
        $freight = M('config')->where('id = 72')->getField('value');
/*        if(!$addressId) {
            if (M('UserAddress')->where(array('user_id' => $user['user_id']))->count()) {
                $address = M('UserAddress')->where(array('user_id' => $user['user_id'], 'is_default' => 1))->find();//获取该用户默认地址若没有默认地址则取第一条若没有地址则提示用户设置地址
                if (!$address) {
                    $address = M('UserAddress')->where(array('user_id' => $user['user_id']))->find();
                }

                $address = $this->getAddress($address);
            }
        }
        else{
            $address = M('UserAddress')->where(array('address_id'=>$addressId))->find();
            $address = $this->getAddress($address);
        }*/
        $goodsList = array();
//        $user = $this->getUser();
        $totle = 0; //总费用
        //从购物车过来
        if($type == 1){
            $cart = I('cart');
            $goods_num = I('goods_num');
            foreach ($cart as $key => $val){
                $goods = M('cart')->where(array('id'=>$key))->find();
                $goods['goods_num'] = $goods_num[$key]; //商品数量 根据前台传过来的数据设置
                $goods['price'] = $goods['goods_num'] * $goods['goods_price']; //商品数量乘上商品价格  每一种商品的总费用
//                $goods['spec_key_name'] = $goods['spec_key_name'];
                $goods['region_pri'] = M('region')->where(array('id'=>$goods['region_id']))->getField('name');
                $goods['region_city'] = M('region')->where(array('id'=>$goods['region_id_2']))->getField('name');
                $goods['original_img'] = M('goods')->where(array('goods_id'=>$goods['goods_id']))->getField('original_img');
                $goodsList[] = $goods; //商品信息
                $totle += $goods['price'];
                M('cart')->where(array('id'=>$key))->delete();//删除购物车
            }
            $totle += $freight;
            $goodsList['totle'] = $totle;
            $goodsList['type'] = 1;
            $type = 1;
        }
        //从立即购买过来
        else if($type==2){
            $goods_id = I("post.goods_id"); // 商品id
            $goods_num = I("post.goods_num");// 商品数量
            $goods_spec = I("post.goods_spec"); // 商品规格
            $specGoodsPriceList = M('SpecGoodsPrice')->where("goods_id = $goods_id")->getField("key,key_name,price,store_count,sku"); // 获取商品对应的规格价钱 库存 条码
            if(!empty($specGoodsPriceList) && empty($goods_spec)) // 有商品规格 但是前台没有传递过来
                $this->ajaxReturn(array('status'=>-1, 'msg'=>'请传递商品规格'));
            $goods = M('goods')->where(array('goods_id'=>$goods_id))->find();
            $goods['goods_num']  = $goods_num;
            $goods['goods_price'] = $goods_spec == '' ? $goods['shop_price'] : $specGoodsPriceList[$goods_spec]['price'];
            $goods['price'] = $goods['goods_num'] * $goods['goods_price']; //商品数量乘上商品价格  每一种商品的总费用
            $goods['spec_key_name'] = $specGoodsPriceList[$goods_spec]['key_name'];
            $goods['spec_key'] = $goods_spec;
            $goods['region_pri'] = M('region')->where(array('id'=>$goods['region_id']))->getField('name');//省份信息
            $goods['region_city'] = M('region')->where(array('id'=>$goods['region_id_2']))->getField('name');//城市信息
//            var_dump($goods_spec);
            $goodsList[] = $goods; //商品信息
            $totle += $goods['price'];
            $totle += $freight;
            $goodsList['totle'] = $totle;
            $goodsList['type'] = 1;
            $type = 1;
        }
        //从特殊商品过来需要去soec_goods表中查找数据
        else if($type == 3){
            $goods_id = I('goods_id');
            $goods = M('SpecGoods')->where(array('id'=>$goods_id))->find();
            $goods['goods_price'] = 0;
            $goods['price'] = 0;
            $goods['goods_num'] = 1;
            $goods['region_pri'] = M('region')->where(array('id'=>$goods['region_id']))->getField('name');
            $goods['spec_key'] = '';
            $goods['original_img'] = $goods['image1'];
            $goodsList[] = $goods; //商品信息
            $totle += $goods['price'];
            $totle += $freight;
            $goodsList['totle'] = $totle;
            $goodsList['type'] = 2;
            $type=2;
        }
        else{
            $goodsList = session('order');
            $totle = $goodsList['totle'];
            $type = $goodsList['type'];
        }
        session('order', $goodsList);
        unset($goodsList['totle']);
        unset($goodsList['type']);

        $this->addOrderOnDB($type, $goodsList);
  /*      if(!$address)
            $no_address = 1;
        else
            $no_address = 0;*/

//        var_dump($no_address);
/*        $this->assign('type', $type);
//        $this->assign('no_address', $no_address);
        $this->assign('totle', $totle);
        $this->assign('freight', $freight);
        $this->assign('goodsList', $goodsList);
//        $this->assign('address', $address);
        $this->display('pay');*/

    }

    public function shop3(){

        $order_id = I('order_id');

        $address_id = I('address_id');

        if($address_id){
            $address = M('UserAddress')->where("address_id = $address_id")->find();
            $data = array(
                'consignee'        =>$address['consignee'], // 收货人
                'province'         =>$address['province'],//'省份id',
                'city'             =>$address['city'],//'城市id',
                'district'         =>$address['district'],//'县',
                'twon'             =>$address['twon'],// '街道',
                'address'          =>$address['area'].$address['address'],//'详细地址',
                'mobile'           =>$address['mobile'],//'手机',
                'zipcode'          =>$address['zipcode'],//'邮编',
                'email'            =>$address['email'],//'邮箱',
                'address_id'       =>$address['address_id'] //地址ID
            );

            M('order')->where(array('order_id'=>$order_id))->save($data);
        }

        if($order_id){

            $order = M('order')->where(array('order_id'=>$order_id, 'is_delete'=>0))->find();
            $goodsList = M('OrderGoods')->where(array('order_id'=>$order['order_id']))->select();

            foreach ($goodsList as $key => $val){
                $goodsList[$key]['price'] = $val['goods_price']*$val['goods_num'];
            }
        }

//        $payback = new PayBackController();
//
//        $payback->weChatPay();

        $this->assign('type', $order['type']);
//        $this->assign('no_address', $no_address);
        $this->assign('totle', $order['order_amount']);
        $this->assign('freight', $order['shipping_price']);
        $this->assign('goodsList', $goodsList);
//        $this->assign('address');
        $this->assign('order', $order);
//        $this->assign('address', $address);
        $this->display('pay');


    }

    public function  shop4(){

        $order_id = I('order_id');
        $user_note = I('user_note');

        $pay_type = I('pay_type');
        $user = $this->getUser();
        if($user_note){

            $data['user_note'] = $user_note;
            M('order')->where(array('order_id'=>$order_id))->save($data);

        }

        if($pay_type == 1) {
            $payLogic = new Logic\PayLogic();
            $re = $payLogic->payByUserMoney($order_id, $user['user_id']);
            $this->ajaxReturn($re);
        }
        else//微信支付
        {
            $this->ajaxReturn(array('status'=>1, 'msg'=>'OK', 'order_id'=> $order_id));

        }
    }


    public function shop5(){
        $useMoney = I('use_money');

        if($useMoney)
            $useMoney = 1;
        else
            $useMoney = 0;
//            var_dump($useMoney);
        $payback = new PayBackController();
        $payback->weChatPay($useMoney);
//        $this->display();


    }

    private function getAddress($address){

        $address['city'] = M('region')->where(array('id'=>$address['city']))->getField('name');
        $address['province'] = M('region')->where(array('id'=>$address['province']))->getField('name');
        $address['district'] = M('region')->where(array('id'=>$address['district']))->getField('name');
        $address['twon'] = M('region')->where(array('id'=>$address['twon']))->getField('name');


        return  $address;

    }


    public function selectAddress(){

        $user = $this->getUser();
        $addressList = M('UserAddress')->where(array('user_id'=>$user['user_id']))->select();
        $flag = 0;
        $order_id = I('order_id');
        if($addressList) {
            foreach ($addressList as $key => $val) {
                $addressList[$key] = $this->getAddress($val);
            }
        }
//        else
//            $flag = 1; //没有地址
        $this->assign('flag', $flag);
        $this->assign('order_id', $order_id);
        $this->assign('addressList', $addressList);
        $this->display();
    }

    public function addOrderOnDB($type,$goodsList){
        $logic = new \Home\Logic\OrderLogic();
        $user = $this->getUser();

//        $this->ajaxReturn(array('status'=>-1, 'msg'=>$post_data));
        $shipping_code='ztoexpress';


        $address = M('UserAddress')->where(array("user_id"=>$user['user_id'], 'is_default'=>1))->find();

        $order_goods = [];
        $i = 0;
        if($type == 1) //普通商品购买
        {
            foreach ($goodsList as $key => $val) {
                $order_goods[$i] = M('Goods')->where(array('goods_id'=>$val['goods_id']))->find();
                $region = M('region')->where(array('id'=>$order_goods[$i]['region_id']))->getField('name');
                $region .=  M('region')->where(array('id'=>$order_goods[$i]['region_id_2']))->getField('name');

                $order_goods[$i]['region_name'] = $region;
                if ($val['spec_key']) {
                    $order_goods[$i]['spec_key'] = $val['spec_key'];
//              $key_name = M('spec_goods_price')->where(array('goods_id' => $val['goods_id'], 'key' => $val['spec_key']))->getField('key_name');
                    $order_goods[$i]['shop_price'] = M('spec_goods_price')->where(array('goods_id' => $val['goods_id'], 'key' => $val['spec_key']))->getField('price');
                } else {
                    $order_goods[$i]['spec_key'] = '';
//                    $key_name = '';
//                    $order_goods[$i]['shop_price'] = $val['shop_price'];
                }

                //判断用户是否为代理商是则将商品价格减去agent_price
                if($user['user_type'] == 1) {
                    $order_goods[$i]['shop_price'] -=  $order_goods[$i]['agent_price'];
                }
                $order_goods[$i++]['goods_num'] = $val['goods_num'];
            }
//            $this->ajaxReturn(array('good'=>$order_goods));
//            $result = new_calculate_price($user['user_id'], $order_goods, $shipping_code, 0, $address[province], $address[city], $address[district], 0, 0, 0, '');
            $result = new_calculate_price($user['user_id'], $order_goods, $shipping_code, 0, 0, 0, 0, 0, 0, 0, '');
            $result['result']['order_prom_id'] = 0 ;
            $result['result']['order_prom_amount'] = 0 ;

            //            $this->ajaxReturn(array('status'=>-1, 'msg'=>$user['user_id']));
        }
        else{//特殊商品购买

//            $goods[] = M('SpecGoods')->where(array('id'=>$post_data['']))
            foreach ($goodsList as $key => $val){

/*                if(M('TakeSpecGoodsLog')->where(array('user_id'=>$user['user_id'], 'goods_id'=>$val['id']))->count())
                    $this->ajaxReturn(array('status'=>-1, 'msg'=>'每个用户只能领取一次'));*/
                $order_goods[$i] = M('SpecGoods')->find($val['id']);
                $order_goods[$i]['spec_key'] = '';
                $order_goods[$i]['goods_num'] = $val['goods_num'];
                $order_goods[$i]['goods_sn'] = '';
                $order_goods[$i]['market_price'] = 0;
                $order_goods[$i]['shop_price'] = 0;
                $order_goods[$i]['original_img'] = $order_goods[$i]['image1'];
                $order_goods[$i]['region_name'] = M('region')->where(array('id'=>$order_goods[$i]['region_id']))->getField('name');
                $order_goods[$i++]['goods_id'] = $val['id'];
            }
//            $this->ajaxReturn(array('status'=>-1, 'msg'=>$order_goods));
            $result['status'] = 1;
            $result['result']['shipping_price'] = M('config')->where('id = 72')->getField('value');
            $result['result']['coupon_price'] = 0;
            $result['result']['user_money'] = 0;
            $result['result']['integral_money'] = 0;
            $result['result']['order_amount'] = M('config')->where('id = 72')->getField('value');
            $result['result']['goods_price'] = 0;
            $result['result']['order_prom_id'] = 0;
            $result['result']['order_prom_amount'] = 0;

        }
        if($result['status'] < 0)
            $this->ajaxReturn($result);
        // 订单满额优惠活动
//                $order_prom = new_get_order_promotion($result['result']['order_amount'], $post_data['promotionIds'][0]);
//
//                $result['result']['order_amount'] = $order_prom['order_amount'] ;
//                $result['result']['order_prom_id'] = $order_prom['order_prom_id'] ;
//                $result['result']['order_prom_amount'] = $order_prom['order_prom_amount'] ;
        $car_price = array(
            'postFee'      => $result['result']['shipping_price'], // 物流费
            'couponFee'    => $result['result']['coupon_price'], // 优惠券
            'balance'      => $result['result']['user_money'], // 使用用户余额
            'pointsFee'    => $result['result']['integral_money'], // 积分支付
            'payables'     => $result['result']['order_amount'], // 应付金额
            'goodsFee'     => $result['result']['goods_price'],// 商品价格
            'order_prom_id' => $result['result']['order_prom_id'], // 订单优惠活动id
            'order_prom_amount' => $result['result']['order_prom_amount'], // 订单优惠活动优惠了多少钱
        );

        $orderSn = date('YmdHis').rand(1000,9999);

        $row = $logic->addOrder($user['user_id'],$address['address_id'],$shipping_code,0,0,$car_price, $order_goods, $orderSn, $type); // 添加订单
        if($row['status'] == 0)
        {
            $this->ajaxReturn(array('status'=>0, 'msg'=>'订单提交成功', 'order_id' =>$row['order_id'] ,'count'=>1));
        }
        else
            $this->ajaxReturn($row);

    }



    public function addOrder(){
        $post_data = I('post.');
//        $post_data = json_decode($post_data, true);
        $logic = new \Home\Logic\OrderLogic();
        $user = $this->getUser();

//        $this->ajaxReturn(array('status'=>-1, 'msg'=>$post_data));
        $shipping_code='ztoexpress';

        if(!$post_data['pay_type'])
            $this->ajaxReturn(array('status'=>-1, 'msg'=>'请选择支付方式'));

        if(!$post_data['addressId'])
            $this->ajaxReturn(array('status'=>-1, 'msg'=>'请选择地址'));

        $address = M('UserAddress')->where("address_id = {$post_data['addressId']}")->find();

        $order_goods = [];
        $i = 0;
        if($post_data['type'] == 1) //普通商品购买
        {
            foreach ($post_data['goodsInfos'] as $key => $val) {
                $order_goods[$i] = M('Goods')->where(array('goods_id'=>$val['goodsId']))->find();
                $region = M('region')->where(array('id'=>$order_goods[$i]['region_id']))->getField('name');
                $region .=  M('region')->where(array('id'=>$order_goods[$i]['region_id_2']))->getField('name');

                $order_goods[$i]['region_name'] = $region;
                if ($val['specKey']) {
                    $order_goods[$i]['spec_key'] = $val['specKey'];
//              $key_name = M('spec_goods_price')->where(array('goods_id' => $val['goods_id'], 'key' => $val['spec_key']))->getField('key_name');
                    $order_goods[$i]['shop_price'] = M('spec_goods_price')->where(array('goods_id' => $val['goodsId'], 'key' => $val['specKey']))->getField('price');
                } else {
                    $order_goods[$i]['spec_key'] = '';
//                    $key_name = '';
//                    $order_goods[$i]['shop_price'] = $val['shop_price'];
                }
                $order_goods[$i++]['goods_num'] = $val['number'];
            }
            $result = new_calculate_price($user['user_id'], $order_goods, $shipping_code, 0, $address[province], $address[city], $address[district], 0, 0, 0, '');

            $result['result']['order_prom_id'] = 0 ;
            $result['result']['order_prom_amount'] = 0 ;

            //            $this->ajaxReturn(array('status'=>-1, 'msg'=>$user['user_id']));
        }
        else{//特殊商品购买

//            $goods[] = M('SpecGoods')->where(array('id'=>$post_data['']))
            foreach ($post_data['goodsInfos'] as $key => $val){

                if(M('TakeSpecGoodsLog')->where(array('user_id'=>$user['user_id'], 'goods_id'=>$post_data['goodsInfos'][0]))->count())
                    return array('status'=>-1, 'msg'=>'每个用户只能领取一次');
                $order_goods[$i] = M('SpecGoods')->find($val['goodsId']);
                $order_goods[$i]['spec_key'] = '';
                $order_goods[$i]['goods_num'] = $val['number'];
                $order_goods[$i]['goods_sn'] = '';
                $order_goods[$i]['market_price'] = 0;
                $order_goods[$i]['shop_price'] = 0;
                $order_goods[$i]['original_img'] = $order_goods[$i]['image1'];
                $order_goods[$i]['region_name'] = M('region')->where(array('id'=>$order_goods[$i]['region_id']))->getField('name');
                $order_goods[$i++]['goods_id'] = $val['goodsId'];
            }
//            $this->ajaxReturn(array('status'=>-1, 'msg'=>$order_goods));
            $result['code'] = 1;
            $result['result']['shipping_price'] = M('config')->where('id = 72')->getField('value');
            $result['result']['coupon_price'] = 0;
            $result['result']['user_money'] = 0;
            $result['result']['integral_money'] = 0;
            $result['result']['order_amount'] = M('config')->where('id = 72')->getField('value');
            $result['result']['goods_price'] = 0;
            $result['result']['order_prom_id'] = 0;
            $result['result']['order_prom_amount'] = 0;

        }
        if($result['code'] < 0)
            $this->ajaxReturn($result);
                // 订单满额优惠活动
//                $order_prom = new_get_order_promotion($result['result']['order_amount'], $post_data['promotionIds'][0]);
//
//                $result['result']['order_amount'] = $order_prom['order_amount'] ;
//                $result['result']['order_prom_id'] = $order_prom['order_prom_id'] ;
//                $result['result']['order_prom_amount'] = $order_prom['order_prom_amount'] ;
        $car_price = array(
            'postFee'      => $result['result']['shipping_price'], // 物流费
            'couponFee'    => $result['result']['coupon_price'], // 优惠券
            'balance'      => $result['result']['user_money'], // 使用用户余额
            'pointsFee'    => $result['result']['integral_money'], // 积分支付
            'payables'     => $result['result']['order_amount'], // 应付金额
            'goodsFee'     => $result['result']['goods_price'],// 商品价格
            'order_prom_id' => $result['result']['order_prom_id'], // 订单优惠活动id
            'order_prom_amount' => $result['result']['order_prom_amount'], // 订单优惠活动优惠了多少钱
        );

        $orderSn = date('YmdHis').rand(1000,9999);


        if(!$post_data['user_note'])
            $user_note = '';
        $row = $logic->addOrder($user['user_id'],$post_data['addressId'],$shipping_code,0,0,$car_price, $order_goods, $orderSn, $post_data['type'], $user_note); // 添加订单
        if($row['status'] == 0)
        {
            $payLogic = new Logic\PayLogic();
//            $this->ajaxReturn(array('status'=>0, 'msg'=>'订单提交成功', 'order_id' =>$row['order_id'] ,'count'=>1));
            if($post_data['pay_type'] == 1)//余额支付
            {
//                $this->ajaxReturn(array('status'=>-1, 'msg'=>'购买成功', 'data'=>$row));
                 $re = $payLogic->payByUserMoney($row['order_id'], $user['user_id']);
                if($re['status'] == 1)
                    $this->ajaxReturn(array('status'=>0, 'msg'=>'购买成功'));
                else
                    $this->ajaxReturn($re);
            }
            else if($post_data['pay_type'] == 2){//微信zhifu
                $this->ajaxReturn(array('status'=>0, 'msg'=>'订单提交成功', 'order_id' =>$row['order_id'] ,'count'=>1));

            }

        }
        else
            $this->ajaxReturn($row);

    }

    public function ajaxShopCartNum(){
        $user = $this->getUser();
        if(empty($user['user_id'])){
            $this->ajaxReturn(array('success'=>false));
        }
        $num = D('Cart')->where(array('user_id'=>$user['user_id']))->count();
        $this->ajaxReturn(array('success'=>true,'num'=>$num));
    }

    public function recharge(){
        $payBack = new PayBackController();
        $payBack->prepareRecharge();
    }

    /**
     * 用于购物车点击改变数量
     */
    public function updateShopCartNum(){
        //获取参数
        $user = $this->getUser();
        $cartId = I('cart_id');
        $num = I('num');
        if($num <= 0)
            $this->ajaxReturn(array('status'=> -1, 'msg'=> '商品数量有误'));
        M('Cart')->where(array('id'=> $cartId, 'user_id'=> $user['user_id']))->setField('goods_num', $num);
        $this->ajaxReturn(array('status'=> 1, 'msg'=> '更新完成'));

    }
}